import '../lib/jquery.js'
import { ajax } from '../utils/ajax.js'
import { pwdTest, nameTest, nickTest } from '../utils/register.js'

$('form').on('submit', async e => {
    //阻止默认行为（不然刷新）
    e.preventDefault();
    //获取注册参数
    let username = $('.username').val();
    let password = $('.password').val();
    let rpassword = $('.rpassword').val();
    let nickname = $('.nickname').val();

    //为空串判断
    if (username == '' || password == '' || rpassword == '' || nickname == '') alert('全部都得填！')

    //判断格式是否正确
    if (!nameTest(username)) alert('用户名格式不对！');
    if (!pwdTest(password)) alert('密码格式不对！');
    if (!nickTest(nickname)) alert('昵称格式不对！');
    if (password != rpassword) alert('两次密码不一样');

    //传到给服务器的数据
    let data = { username, password, rpassword, nickname };
    //请求
    let { data: { code } } = await ajax.post('/users/register', data)


    //失败，并让你看见失败标签
    if (code == 0) return $('.error').css('display', 'block');

    alert('注册成功,点击跳转到登录界面')
    //成功
    location.href = './login.html'
})
